<?php

namespace addons\cloud_market\controller\api;

use hiduoke\controller\BaseAddonsController;
use addons\cloud_market\model\CloudMarketUser;
use addons\cloud_market\model\CloudMarketDeveloper;
use addons\cloud_market\utils\CloudMarketToken;
use think\App;

class CloudMarketApiController extends BaseAddonsController
{
    protected $notLogin = "*";
    protected $notCheck = "*";

    /**
     * API不需要登录的方法
     * @var array|string
     */
    protected $notApiLogin = [];

    /**
     * API不需要权限检查的方法
     * @var array|string
     */
    protected $notApiCheck = [];

    /**
     * 当前登录用户
     * @var CloudMarketUser
     */
    protected $userInfo = null;

    /**
     * 当前用户Token
     * @var string
     */
    protected $UserToken = '';

    /**
     * 当前开发者信息
     * @var CloudMarketDeveloper
     */
    protected $developer = null;

    public function __construct(App $app)
    {
        parent::__construct($app);

    }

    protected function initialize()
    {
        parent::initialize();
        force_json();
        // 初始化用户认证
        $this->initUserAuth();
        // 检查操作权限
        $this->checkApiPermission();
    }


    protected function initUserAuth()
    {
        if ($this->auth->isLogin()) {
            // 获取的是后台的用户信息
            $this->systemUserInfo = $this->auth->getUserinfo();
            $this->UserToken = $this->auth->getToken();
            // 当前用户信息
            $this->userInfo = (new CloudMarketUser())->where(['uid'=>$this->systemUserInfo['uid']])->append(['developer'])->find();
            $developerModel = new CloudMarketDeveloper();
            $this->developer = $developerModel->where('user_id', $this->userInfo->id)->find();
        } else {
            if (!$this->match($this->notApiLogin)) {
                showMessage('未找到登录账号信息', 'error', '', 401);
            }
        }
    }

    /**
     * 初始化用户认证
     */
    protected function initAuth()
    {
        $UserToken = $this->request->header('access-token') ?: $this->request->param('access-token');
        if ($UserToken) {
            $this->UserToken = $UserToken;
            $data = CloudMarketToken::get($UserToken);
            if ($data && isset($data['uid'])) {
                $userModel = new CloudMarketUser();
                $user = $userModel->append(['developer', 'message_count'])->find($data['uid']);
                if ($user && !$user->delete_time) {
                    $this->userInfo = $user;
                    // 获取开发者信息
                    $developerModel = new CloudMarketDeveloper();
                    $this->developer = $developerModel->where('user_id', $user->id)->find();
                } else {
                    if (!$this->match($this->notApiLogin)) {
                        showMessage('未找到登录账号信息', 'error', '', 401);
                    }
                }
            } else {
                if (!$this->match($this->notApiLogin)) {
                    showMessage('UserToken已过期', 'error', '', 401);
                }
            }
        } else {
            if (!$this->match($this->notApiLogin)) {
                showMessage('无账号登录信息', 'error', '', 401);
            }
        }
    }

    /**
     * 匹配控制器的方法
     *
     * @param array|string $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($arr = [])
    {
        $request = request();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }
        return false;
    }

    /**
     * TODO 检查API操作权限
     */
    protected function checkApiPermission()
    {
        $action = $this->request->action();

        // 如果notApiCheck为*，表示所有方法都不需要权限检查
        if ($this->notApiCheck === '*') {
            return;
        }

        // 如果notApiCheck为数组，检查当前方法是否在不需要权限检查的列表中
        if (is_array($this->notApiCheck) && in_array($action, $this->notApiCheck)) {
            return;
        }

        // 用户未登录，无法进行权限检查
        if (!$this->userInfo) {
            return; // 登录检查已经在checkApiLogin中处理
        }

        // 普通用户不需要权限检查，只有开发者需要检查权限
        if (!$this->developer) {
            return;
        }

        // 检查开发者权限
        $this->checkDeveloperPermission($action);
    }

    /**
     * TOTO 检查开发者权限
     *
     * @param string $action 当前操作方法
     */
    protected function checkDeveloperPermission($action)
    {
        if (!$this->developer || !$this->developer->rule) {
            $this->error('无权限访问', null, 403);
        }

        $rules = $this->developer->rule ?? [];
        if (!is_array($rules)) {
            $this->error('权限配置错误', null, 403);
        }
        // 获取当前控制器名称
        $controller = $this->request->controller();
        $permission = strtolower($controller . '/' . $action);
        // 检查是否有对应权限
        if (!in_array($permission, $rules) && !in_array('*', $rules)) {
            $this->error('无权限执行此操作', null, 403);
        }
    }

    /**
     * 获取当前登录用户
     *
     * @return CloudMarketUser|null
     */
    protected function getUser()
    {
        return $this->userInfo;
    }

    /**
     * 获取当前用户Token
     *
     * @return string
     */
    protected function getToken()
    {
        return $this->UserToken;
    }

    /**
     * 获取当前开发者信息
     *
     * @return CloudMarketDeveloper|null
     */
    protected function getDeveloper()
    {
        return $this->developer;
    }

    /**
     * 检查是否为开发者
     *
     * @return bool
     */
    protected function isDeveloper()
    {
        return $this->developer !== null;
    }
}
